package com.roc.web.action.orgmain;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.AreaBean;
import com.roc.bean.orgMainBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.ServiceException;
import com.roc.service.area.IAreaService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.service.orgmain.IOrgMainService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
@SuppressWarnings("serial")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/orgmain")
public class OrgMainAction extends PaginationBaseAction {
	private static final String String = null;
	private Logger logger=LogManager.getLogger(OrgMainAction.class);
	private OrgMainSearchCondition searchCondition;
	private orgMainBean orgmain;
	
	private List<AreaBean> areaCodeList = new ArrayList<AreaBean>();
	
	@Autowired
	private IPowerInfoService  powerInfoService;
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IAreaService areaService;
	
	@Autowired
	IOrgMainService orgMainService;


	/**
	 * 初始化区域jsp
	 * @Title: init
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @throws Exception
	 *
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/orgmain/queryOrg.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })	
	public String init() throws Exception{
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
		String superRole= map.get("superRole");
		if(!(op.getRoleType().equals(Role.SYSTEM.getCode())
				||(superRole.equals(Role.SYSTEM.getCode())&&(op.getRoleType().equals(Role.OPERATORS_COMM.getCode())||op.getRoleType().equals(Role.OPERATORS_LEAD.getCode()))))){
			addActionMessage("当前用户没有权限！");
			  return ERROR;
		}
		    areaInf();
			return SUCCESS;
    }

	/**
	 * 查询现有机构
	 * @Title: queryAreaList
	 * @Description:TODO(...))
	 * @see <p></p>
	 * @return
	 * @throws Exception
	 * @author jjj
	 * @date: 2017年8月29日 
	 *
	 */
	@Action(value = "queryOrg", results = { @Result(name = "success", location = "/pages/orgmain/queryOrg.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryOrg() throws Exception{
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		areaInf();
		logger.info("查询现有区域开始......");
		try {
			if(searchCondition==null){
				searchCondition=(OrgMainSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new OrgMainSearchCondition();
				}
			}
			Map<String, String> map=powerInfoService.queryRealIdByOpId(op.getSuperiorId(), op.getRoleType(), op.getId(), op.getOrgCode());
			String superRole= map.get("superRole");
			if(!(op.getRoleType().equals(Role.SYSTEM.getCode())
					||(superRole.equals(Role.SYSTEM.getCode())&&(op.getRoleType().equals(Role.OPERATORS_COMM.getCode())||op.getRoleType().equals(Role.OPERATORS_LEAD.getCode()))))){
				addActionMessage("当前用户没有权限！");
				  return ERROR;
			}
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<orgMainBean> orgList = new ArrayList<orgMainBean>();
			queryOrgList(orgList,searchRsList);
			getRequest().setAttribute("orgList", orgList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}		
	   return SUCCESS;
    }
	/**
	 * 查询机构数据
	 * @Title: queryAreaList
	 * @Description:TODO(...)
	 * @see <p></p>
	 *
	 */
	 public  void queryOrgList(List<orgMainBean> orgList,List<Object> searchRsList){
		    
			if(searchRsList!=null&&searchRsList.size()>0){
				Iterator iterator=searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj=(Object[]) iterator.next();
					orgMainBean bean=new orgMainBean();
					bean.setOrgCode(Constance.Null2EmptyTrim(obj[0]));
					bean.setOrgName(Constance.Null2EmptyTrim(obj[1]));
					bean.setAreaName(Constance.Null2EmptyTrim(obj[2]));
					bean.setSuperName(Constance.Null2EmptyTrim(obj[3]));
					bean.setOprName(Constance.Null2EmptyTrim(obj[4]));
					bean.setCrtTs(Constance.Null2EmptyTrim(obj[5]));
					bean.setStatus(Constance.Null2EmptyTrim(obj[6]));
					orgList.add(bean);
			}
			
			
		}
	 }
	/**
	 * 初始化添加机构
	 * @Title: addAreajsp
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 *
	 */
	@Action(value = "addOrgjsp", results = { @Result(name = "success", location = "/pages/orgmain/addOrg.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addOrgjsp()
	{
		areaInf();
		orgmain=new orgMainBean();
		orgmain.setCrtTs(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

		return SUCCESS;		
	}
	/**
	 * 增加机构
	 * @Title: addBlackList
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @throws Exception 
	 *
	 */
	@Action(value = "addOrg", results = { @Result(name = "success", location = "/pages/orgmain/addOrg.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addOrg() throws Exception
	{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			boolean value =orgMainService.addOrgList(orgmain, op);
			if(value){
				addActionMessage("添加成功!");
			}else{
				addActionMessage("所要添加的机构已经存在!");
			}
			//queryOrg();
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("添加机构失败~");
		}
		return SUCCESS;		
	}

	/**
	 * 修改区域页面初始化
	 * @Title: updateAreaJsp
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 *
	 */
	@Action(value = "updateOrgJsp", results = { @Result(name = "success", location="/pages/orgmain/addOrg.jsp")})
	public String updateOrgJsp()
	{
		try {
			areaInf();
			orgmain=orgMainService.findOrgByCode(orgmain.getOrgCode());
		
			orgmain.setOrgCode(orgmain.getOrgCode());
			orgmain.setOrgName(orgmain.getOrgName());
			orgmain.setAreaName(orgmain.getAreaName());
			orgmain.setSuperName(orgmain.getSuperName());
			orgmain.setOprName(orgmain.getOprName());
			orgmain.setCrtTs(orgmain.getCrtTs());
			getRequest().setAttribute("flag", "update");
		} catch (ServiceException e) {
			e.printStackTrace();
			e.getMessage();
			addActionError("修改机构页面初始化失败~");
		}
		return SUCCESS;
	}
	/**
	 * 修改区域
	 * @Title: updateStatus
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @throws Exception 
	 * @date: 2017年8月7日 下午3:28:57
	 *
	 */
	@Action(value = "updateOrg", results = { @Result(name = "success", location="/pages/orgmain/addOrg.jsp")})
	public String updateOrg() throws Exception
	{
		areaInf();
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			orgmain.setOrgName(orgmain.getOrgName());
			orgmain.setAreaId(orgmain.getAreaId());
			orgmain.setSuperId(op.getOrgCode());
			orgmain.setOprId(String.valueOf(op.getId()));
			orgmain.setUpTs(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			orgmain.setStatus(orgmain.getStatus());
			
			int c = orgMainService.updateOrgList(orgmain, op);
			if(c>0){
				addActionMessage("修改成功!");
			}else{
				addActionMessage("修改失败!");
			}
			//queryOrg();
		} catch (ServiceException e) {
			e.printStackTrace();
			addActionError("更改机构信息失败~");
		}
		return SUCCESS;
	}
	
	
	/**
     * 初始化区域名称
     * @Title: insInf
     * @Description: TODO
     * @param @return    
     * @return String    
     * @throws
     */
	public String areaInf(){
		try {
		    Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		    areaCodeList = areaService.queryAreaInf(op);
		} catch (Exception e) {
			addActionError("加载机构失败，请联系客服人员");
			logger.error(e.getMessage(),e);
		}
		return SUCCESS;
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {

		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {

		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {

		getSession().setAttribute(SEARCH_SESSION_TBL_AREA, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {

		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_TBL_AREA);
	}



	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE+"";
	}

	public OrgMainSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(OrgMainSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public orgMainBean getOrgmain() {
		return orgmain;
	}

	public void setOrgmain(orgMainBean orgmain) {
		this.orgmain = orgmain;
	}

	public List<AreaBean> getAreaCodeList() {
		return areaCodeList;
	}

	public void setAreaCodeList(List<AreaBean> areaCodeList) {
		this.areaCodeList = areaCodeList;
	}

	

	
}

